package com.lunhui.search.provider.clientImpl;

import com.alibaba.fastjson.JSONObject;
import com.lunhui.search.business.UserService;
import com.lunhui.search.client.UserSearchClient;
import com.lunhui.search.client.model.UserSearchDto;
import com.lunhui.search.dal.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author renminghe-kg
 */

@Service
public class UserSearchServiceImpl implements UserSearchClient {
    @Autowired
    @Qualifier("userService")
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserSearchServiceImpl.class);

    @Override
    public UserSearchDto searchByAccount(String account) throws IOException,RuntimeException {
        try {
            User user = userService.searchByName(account);
            if (user == null) {
                return null;
            }

            UserSearchDto userSearchDto = new UserSearchDto();
            BeanUtils.copyProperties(user, userSearchDto);

            logger.info("接口searchByAccount返回: " + JSONObject.toJSONString(userSearchDto));

            return userSearchDto;

        } catch (IOException e) {
            logger.error("获取ES User数据异常: " + e.getMessage());
            throw new IOException("获取ES User数据异常: " + e.getMessage());
        } catch (Exception e) {
            logger.error("获取ES User数据异常: " + e.getMessage());
            throw new RuntimeException("获取ES User数据异常: " + e.getMessage());
        }
    }

    @Override
    public Integer addUserAccount(UserSearchDto userSearchDto) throws IOException,RuntimeException {
        try {
            User user = new User();
            BeanUtils.copyProperties(userSearchDto, user);

            logger.info("新增账号成功: " + JSONObject.toJSONString(userSearchDto));

            return userService.addUserAccount(user);
        } catch (IOException e) {
            logger.error("添加ES User数据异常: " + e.getMessage());
            throw new IOException("添加ES User数据异常: " + e.getMessage());
        } catch (Exception e) {
            logger.error("添加ES User数据异常: " + e.getMessage());
            throw new RuntimeException("添加ES User数据异常: " + e.getMessage());
        }
    }
}